// components/Console/VNCConsole.tsx
import React, { useEffect, useRef, useState } from 'react';
import { consoleService } from '../../services/console';

interface VNCConsoleProps {
  connection: string;
  domainName: string;
  className?: string;
}

const VNCConsole: React.FC<VNCConsoleProps> = ({
  connection,
  domainName,
  className = ''
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const connectVNC = async () => {
      try {
        // 验证输入参数
        if (!connection || !domainName) {
          throw new Error('Connection and domain name are required');
        }

        // 获取VNC信息
        const vncInfo = await consoleService.getVNCInfo(connection, domainName);

        if (!vncInfo.host || !vncInfo.port) {
          throw new Error('VNC connection information not available');
        }

        // 设置连接状态
        setLoading(true);
        setError(null);

        // 占位符：这里应该实现VNC连接逻辑
        // 但由于已移除noVNC依赖，此处暂不实现具体连接
        console.log('VNC connection info:', vncInfo);
        setLoading(false);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : 'Failed to connect to VNC console';
        setError(errorMessage);
        setLoading(false);
        console.error('VNC connection error:', err);
      }
    };

    // 只有当connection和domainName都存在时才连接
    if (connection && domainName) {
      connectVNC();
    }

    // 清理函数
    return () => {
      // 这里可以添加任何必要的清理逻辑
    };
  }, [connection, domainName]);

  return (
    <div className={`vnc-console ${className}`}>
      {loading && (
        <div className="flex items-center justify-center h-full">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
        </div>
      )}
      
      {error && (
        <div className="flex items-center justify-center h-full">
          <div className="text-red-500 p-4 border border-red-500 rounded">
            Error: {error}
          </div>
        </div>
      )}
      
      {!loading && !error && (
        <div className="h-full">
          <canvas 
            ref={canvasRef} 
            className="w-full h-full"
          />
        </div>
      )}
    </div>
  );
};

export default VNCConsole;